package com.bestom.smartwatch.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bestom.smartwatch.R;
import com.bestom.smartwatch.adapter.IconAdapter;
import com.bestom.smartwatch.bean.IconBean;
import com.bestom.smartwatch.manage.SQLiteManage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.bestom.smartwatch.SmartWatchApplication.nowDeviceId;
import static com.bestom.smartwatch.util.LogUtil.log;

public class SettingActivity extends BaseActivity{

    @BindView(R.id.name_spinner)
    Spinner nameSpinner;
    @BindView(R.id.time_TextView)
    TextView mTimeTextView;
    @BindView(R.id.select)
    TextView select;
    @BindView(R.id.select_listView)
    ListView selectListView;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.modification)
    TextView modification;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.device_id)
    TextView deviceId;
    @BindView(R.id.pop_student_name)
    TextView popStudentName;
    @BindView(R.id.pop_student_id)
    TextView popStudentId;
    @BindView(R.id.pop_student_class)
    TextView popStudentClass;

    private Context mContext;
    private SQLiteManage mSQLiteManage;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mContext = this;
        setContentView(R.layout.activity_setting);
        super.onCreate(savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                setInfo();
            }
        }).start();

        setListener();
    }

    @Override
    protected void initView() {
    }

    private List<IconBean> mIconBeenList;
    private IconAdapter iconAdapter;
    private String selectName = null;
    private String selectTime = null;
    @Override
    protected void initData() {
        mIconBeenList = new ArrayList<>();
        mSQLiteManage = new SQLiteManage(mContext);
        iconAdapter = new IconAdapter(mContext, mIconBeenList);
        selectListView.setAdapter(iconAdapter);
        mItemArrayList = new ArrayList<>();
    }

    private ArrayList<String> mItemArrayList;
    private ArrayAdapter<String> adapter;
    String studentName = "";
    String studentId = "";
    String studentClass = "";
    private void setInfo(){
        Cursor cursor = mSQLiteManage.select(nowDeviceId);

        if (cursor.getCount() > 0){
            while (cursor.moveToNext()){
                studentName = cursor.getString(cursor.getColumnIndex("students_name"));
                studentId = cursor.getString(cursor.getColumnIndex("students_id"));
                studentClass = cursor.getString(cursor.getColumnIndex("students_class"));

                popStudentName.setText(studentName);
                popStudentId.setText(studentId);
                popStudentClass.setText(studentClass);
            }
            cursor.close();
        }

        Cursor cursorAll = mSQLiteManage.selectAll();

        mItemArrayList.add("全部");
        if (cursorAll.getCount() > 0){
            while (cursorAll.moveToNext()){
                String name = cursorAll.getString(cursor.getColumnIndex("students_name"));
                mItemArrayList.add(name);
            }
            cursorAll.close();
        }
        adapter = new ArrayAdapter<>(mContext,android.R.layout.simple_spinner_item, mItemArrayList);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        nameSpinner.setAdapter(adapter);

    }

    private void setListener(){
        nameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                selectName = mItemArrayList.get(pos);
                if (selectName.equals("全部")) selectName = null;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        mTimeTextView.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                String[] timeS= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).split("-");
                selectTime = null;
                mTimeTextView.setText("所有日期");
                new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        selectTime = year + "-" + monthOfYear + "-" + dayOfMonth;
                        mTimeTextView.setText(selectTime);
                    }
                }, Integer.parseInt(timeS[0]), Integer.parseInt(timeS[1]), Integer.parseInt(timeS[2])).show();
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectToShow(selectName, selectTime);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int result = saveStudentInfo(nowDeviceId, popStudentName.getText().toString().trim(), popStudentId.getText().toString().trim(), popStudentClass.getText().toString().trim());
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popStudentClass.setEnabled(false);
                if (result == 1) Toast.makeText(getApplicationContext(),"添加成功",Toast.LENGTH_SHORT).show();
                else Toast.makeText(getApplicationContext(),"修改成功",Toast.LENGTH_SHORT).show();

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popStudentName.setText(studentName);
                popStudentId.setText(studentId);
                popStudentClass.setText(studentClass);
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popStudentClass.setEnabled(false);
            }
        });
        modification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popStudentName.setEnabled(true);
                popStudentId.setEnabled(true);
                popStudentClass.setEnabled(true);
            }
        });
    }
    private void selectToShow(String selectName, String selectTime) {

        Cursor cursor = mSQLiteManage.selectStudentAllDataByNameAndTime(selectName, selectTime);
        mIconBeenList.clear();
        if (cursor.getCount() > 0){
            while (cursor.moveToNext()){
                IconBean mIconBean = new IconBean(
                        cursor.getString(cursor.getColumnIndex("students_name")),
                        cursor.getString(cursor.getColumnIndex("students_max_temp")),
                        cursor.getString(cursor.getColumnIndex("students_body_temp")),
                        cursor.getString(cursor.getColumnIndex("students_skin_temp")),
                        cursor.getString(cursor.getColumnIndex("students_step")),
                        cursor.getString(cursor.getColumnIndex("students_calories")),
                        cursor.getString(cursor.getColumnIndex("students_distance")),
                        cursor.getString(cursor.getColumnIndex("students_heart_rate")),
//                        cursor.getString(cursor.getColumnIndex("students_systolic_blood_pressure")),
//                        cursor.getString(cursor.getColumnIndex("students_diastolic_blood_pressure")),
                        cursor.getString(cursor.getColumnIndex("students_blood_oxygen")),
                        cursor.getString(cursor.getColumnIndex("students_time")));
                mIconBeenList.add(mIconBean);
            }
            cursor.close();
        }else {
            Toast.makeText(getApplicationContext(),"未查询到数据",Toast.LENGTH_SHORT).show();
        }
        iconAdapter.notifyDataSetChanged();
    }

    private int saveStudentInfo(String deviceId, String popStudentName, String popStudentId, String popStudentClass){
        boolean exist = mSQLiteManage.exist(deviceId);
        if (exist){
            mSQLiteManage.update(deviceId, popStudentName, popStudentId, popStudentClass);
            return 0;
        }else {
            mSQLiteManage.add(deviceId, popStudentName, popStudentId, popStudentClass);
            return 1;
        }
    }
}
